<script setup>
import { ref, onMounted } from 'vue'
import { sessionApi, treeMenusApi, pageBtnsApi, sortBtnApi, saveBtnApi, oneBtnApi, delBtnsApi } from '@/commons/api'
import routes from '@/commons/router'
import TreeSel from '@/components/cascader/TreeSel.vue'
import Loader from '@/components/loader/Loader.vue'
import { CScrollbar } from 'c-scrollbar'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager.vue'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let procAuth = {
  addAuth: false,
  delAuth: false,
  edtAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      procAuth = {
        addAuth: userBtnCode.indexOf('1001010301') !== -1,
        delAuth: userBtnCode.indexOf('1001010302') !== -1,
        edtAuth: userBtnCode.indexOf('1001010303') !== -1
      }
      await selMenus()
      await list(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const schObj = {
  keywords: '',
  menuId: '',
  menuName: '',
  menuCode: '',
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const btnList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageBtnsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    btnList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    menuId: '',
    menuName: '',
    menuCode: '',
    offset: 0,
    limit: 20
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    btnList.value.forEach(item => {
      idList.value.push(item.btnId)
      checkList.value.push(true)
    })
  } else {
    btnList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, roleId) => {
  if(!checkList.value[idx]) {
    idList.value.push(roleId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === roleId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const btnForm = ref({
  btnId: '',
  btnName: '',
  btnCode: '',
  menuId: '',
  sort: 0
})
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (btnId) => {
  const res = await oneBtnApi({ btnId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    showModal.value = true
    btnForm.value = res.data
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let btnName = btnForm.value.btnName
  let btnCode = btnForm.value.btnCode
  let menuId = btnForm.value.menuId
  let sort = parseInt(btnForm.value.sort)
  if(btnName === '' || btnName.length > 50) {
    Msg({ kind: 'warn', txt: '按钮名称不能为空，且长度不超过10个字符！' })
    return
  } else if(btnCode === '' || btnCode.length > 30) {
    Msg({ kind: 'warn', txt: '按钮编码不能为空，且长度为10位的数字编码！' })
    return
  } else if(menuId === '' || menuId.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择所属菜单！' })
    return
  } else if(sort === 0) {
    Msg({ kind: 'warn', txt: '请输入按钮排序，必须为数字！' })
    return
  }
  btnForm.value.sort = sort
  loadShow.value = true
  try {
    const res = await saveBtnApi(btnForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，按钮信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  btnForm.value = {
    btnId: '',
    btnName: '',
    btnCode: '',
    menuId: '',
    sort: 0
  }
}

// deletes 删除按钮
const deletes = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再删除！' })
    return
  }
  Confirm('确定要删除选中的按钮吗？').then(() => {
    delBtns()
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消删除选中的数据！" })
  })
}
// delBtns 删除按钮实现，分离出来防止调用时异步报错
const delBtns = async () => {
  let btnIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await delBtnsApi({ btnIds })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，按钮信息删除成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// 所有菜单数组
const menuList = ref([])
// selMenus 获取菜单及按钮列表
const selMenus = async () => {
  const res = await treeMenusApi()
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    menuList.value = res.data
  }
}

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.menuId = item.selId
      schRef.value.menuName = item.selName
      schRef.value.menuCode = item.selCode
      break
    case 2:
      sort(item.selId, item.selCode)
      btnForm.value.menuId = item.selId
      btnForm.value.menuName = item.selName
      btnForm.value.menuCode = item.selCode
      break
  }
}

// sort 按钮排序
const sort = async (menuId, menuCode) => {
  const res = await sortBtnApi({ menuId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    btnForm.value.sort = res.data
    btnForm.value.btnCode = menuCode + '0' + res.data
  }
}
</script>

<template>
  <div class="a">
    <div class="b">
      <div class="c">
        <div v-if="procAuth.addAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="procAuth.delAuth" class="btn-de mr15" title="删除" @click="deletes"><i class="iconfont">&#xea45;</i> 删除</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 系统管理 > 按钮管理</div>
    </div>
    <div v-show="schShow" class="e">
      <div class="mr15 mt10"><tree-sel :kind="1" :tree-list="menuList" :inboxed="true" :curName="schRef.menuName!=='' ? schRef.menuName+'['+schRef.menuCode+']' : ''" pre-name="所属菜单" @setValue="setValue" /></div>
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="f mt10">
        <div class="btn-pi mr15" title="搜索" @click="list(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 10%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 25%;">菜单</th>
            <th style="width: 15%;">名称</th>
            <th style="width: 20%;">编码</th>
            <th style="width: 15%;">排序</th>
            <th style="width: 15%;">操作</th>
          </tr>
          <tr v-for="(curBtn, index) in btnList" :key="curBtn.btnId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, curBtn.btnId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td class="txt-center">{{curBtn.menuName}}[{{curBtn.menuCode}}]</td>
            <td class="txt-center">{{curBtn.btnName}}</td>
            <td class="txt-center">{{curBtn.btnCode}}</td>
            <td class="txt-center">{{curBtn.sort}}</td>
            <td class="txt-center">
              <span v-if="procAuth.edtAuth" class="cl-warn" title="修改" @click="update(curBtn.btnId)"><i class="iconfont">&#xea48;</i> 修 改</span>
            </td>
          </tr>
        </tbody>
      </table>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存按钮信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>按钮名称</div>
                <div><input type="text" v-model="btnForm.btnName" maxlength="50" placeholder="请输入按钮名称" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>所属菜单</div>
                <tree-sel :tree-list="menuList" :kind="2" :inboxed="false" :curName="btnForm.menuName ? btnForm.menuName+'['+btnForm.menuCode+']' : ''" pre-name="所属菜单" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>按钮编码</div>
                <div><input type="text" v-model="btnForm.btnCode" maxlength="10" placeholder="请输入按钮编码" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>按钮排序</div>
                <div><input type="text" v-model="btnForm.sort" maxlength="30" placeholder="请输入按钮排序" class="ipt" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.a {padding: 10px;}
.b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.c {display: inline-flex; display: -webkit-inline-flex;}
.d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.f {display: inline-flex; display: -webkit-inline-flex;}
</style>